package com.example.consumer.direct;


import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;

/**
 * 先注释 DirectReceiver的@Component
 * 用TestAckDirectReceiver方法来验证 手动ack
 */
@Slf4j
@Component
public class TestAckDirectReceiver {
    public static final String TestDirectQueue = "TestDirectQueue";
    public static final String TestDirectExchange = "TestDirectExchange";
    public static final String TestDirectRouting = "TestDirectRouting";

    @RabbitListener(queues = TestAckDirectReceiver.TestDirectQueue,
            ackMode= "MANUAL")
    @RabbitHandler
    public void receiver(@Payload HashMap dataMsg, Channel channel, Message message) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        log.info("消费者1号 deliveryTag:{} dataMsg:{} ",deliveryTag ,dataMsg);
        try {
           int i = 1/0;
        } catch (Exception e) {
            log.error("MyAckReceiver error : {}  deliveryTag:{}",e.getMessage(),deliveryTag);
            //消息重新投递
            channel.basicReject(deliveryTag, true);
        }

    }

    @RabbitListener(queues = TestAckDirectReceiver.TestDirectQueue,
            ackMode= "MANUAL")
    @RabbitHandler
    public void receiver1(@Payload HashMap dataMsg, Channel channel, Message message) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        log.info("消费者2号 deliveryTag:{} dataMsg:{} ",deliveryTag ,dataMsg);
        channel.basicAck(deliveryTag,true);
    }

}
